<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <areas :areas="treeAreas" :area-type="areaType"  v-on:handleNodeClick="onHandleNodeClick" />
      </el-col>
      <el-col :span="20" :xs="24">
        <el-card>
          <div class="filter-container">
            <el-date-picker
              style="margin-left: 20px;"
              class="filter-item"
              v-model="dateRange"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
              placeholder="选择时间">
            </el-date-picker>
            <el-button   style="margin-left:40px" class="filter-item" type="primary" icon="el-icon-search" @click="fetchList">
              查询
            </el-button>
            <el-button   style="margin-left:20px" class="filter-item" type="primary" icon="el-icon-download" @click="exportData">
              导出
            </el-button>
          </div>
          <div class="app-container">
            <el-table
              :key="tableKey"
              v-loading="listLoading"
              :data="list"
              :span-method="objectSpanMethod"
              ref="waterTable"
              :row-style="{height:40+'px'}"
              :cell-style="{padding:0+'px'}"
              border
              fit
              stripe
              highlight-current-row
              height="700"
              style="width: 100%;"
            >
              <el-table-column
                type="index"
                label="#"
                align="center"
                width="50">
              </el-table-column>
              <el-table-column label="账户名" prop="name" align="center" >
                <template v-slot="{row}">
                  <span>{{row.name }}</span>
                </template>
              </el-table-column>
              <el-table-column label="用户类型" align="center" >
                <template v-slot="{row}">
                  <span>{{row.typ_text }}</span>
                </template>
              </el-table-column>
              <el-table-column label="交易数" align="center"  >
                <template v-slot="{row}">
                  <span>{{row.count}}</span>
                </template>
              </el-table-column>
              <el-table-column  label="金额(元)" prop="amount"  align="center">
                <template v-slot="{row}">
                  <span>{{row.amount}}</span>
                </template>
              </el-table-column>
              <el-table-column  label="用水量(m³)"  align="center">
                <template v-slot="{row}">
                  <span>{{row.usage_amount}}</span>
                </template>
              </el-table-column>
              <el-table-column  label="小计金额(元)"  align="center">
                <template v-slot="{row}">
                  <span>{{row.subtotalAmount}}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import areas from '@/components/area/AreaTree'
import Pagination from '@/components/Pagination'
import {waterAmount} from "@/api/meter";
import {getAreaTree} from "@/api/area";
import LineChart from "@/views/equip/components/LineChart";
import {checkPermission} from "@/utils/permission";
import {financePaymentReport} from "@/api/analysis";
import moment from "moment";
import {exportExcel} from "@/utils/excel";

export default {
  name: 'FinancePaymentReport',
  components:{areas,Pagination},
  data() {
    return {
      tableKey:0,
      exportLoading:false,
      listLoading:true,
      list:[],
      spanArr: [],
      total:0,
      areaType:2,
      dateType:'month',
      dateRange:null,
      listQuery:{
        start:'',
        end:'',
        code:'',
        is_contains_sub: this.$store.getters.showSubData,
      },
      treeAreas:[],
      types:[
        { label: '年报', value: 'year'},
        { label: '月报', value: 'month' },
        { label: '日报', value: 'date' },
      ],
      pickerOptions: {
        shortcuts: [ {
          text: '月报',
          onClick(picker) {
            const d = new Date();
            picker.$emit('pick', [moment(d).startOf('month'), moment(d).endOf('month')]);
          }
        }, {
          text: '年报',
          onClick(picker) {
            const d = new Date();
            picker.$emit('pick', [moment(d).startOf('year'), moment(d).endOf('year')]);
          }
        }]
      },
    }
  },
  created() {
    this.dateRange = [moment().startOf('month'), moment().endOf('month')]
    this.fetchList()
    this.getAreaTree()
  },
  methods: {
    checkPermission,
    getAreaTree(type){
      getAreaTree({type:2,is_contains_sub: this.$store.getters.showSubData}).then(response => {
        this.treeAreas = response.data
      })
    },
    onHandleNodeClick:function (data) {
      if(this.listQuery.code !== data.code){
        this.listQuery.code = data.code
        this.fetchList()
      }
    },
    calculateSubtotalAmount() {
      const nameMap = {};
      this.list.forEach(item => {
        if (!nameMap[item.name]) {
          nameMap[item.name] = {
            total: 0,
            count: 0
          };
        }
        nameMap[item.name].total += parseFloat(item.amount);
        nameMap[item.name].count++;
      });
      this.list.forEach(item => {
        item.subtotalAmount = nameMap[item.name].total;
      });
    },
    getSpanArr() {
      this.spanArr = [];
      let pos = 0;
      for (let i = 0; i < this.list.length; i++) {
        if (i === 0) {
          this.spanArr.push(1);
          pos = 0;
        } else {
          if (this.list[i].name === this.list[i - 1].name) {
            this.spanArr[pos]++;
            this.spanArr.push(0);
          } else {
            this.spanArr.push(1);
            pos = i;
          }
        }
      }
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      const lastColumnIndex = 6;
      if (columnIndex === 0 || columnIndex === 1 || columnIndex === lastColumnIndex) {
        const _row = this.spanArr[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col,
        };
      }
    },
    fetchList(){
      let data = Object.assign({},this.listQuery)
      if(this.dateRange && this.dateRange.length>1){
        data.start = moment(this.dateRange[0]).format('yyyy-MM-DD')
        data.end = moment(this.dateRange[1]).format('yyyy-MM-DD')
      }

      this.listLoading = true
      financePaymentReport(data).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        if(this.list){
          this.calculateSubtotalAmount(); // 计算金额小计
          this.getSpanArr(); // 计算合并行
        }
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    exportData(){
      this.exportLoading = true
      let data = Object.assign({},this.listQuery)
      if(this.dateRange && this.dateRange.length>1){
        data.start = moment(this.dateRange[0]).format('yyyy-MM-DD')
        data.end = moment(this.dateRange[1]).format('yyyy-MM-DD')
      }
      financePaymentReport(data).then(response => {
        if (response.code === 20000) {
          const tHeader = ['账户名', '用户类型', '交易数', '金额(元)', '用水量(m³)']
          const  list = response.data.list.map(item => ({
            '账户名': item.name,
            '用户类型': item.typ_text,
            '交易数': item.count,
            '金额(元)': item.amount,
            '用水量(m³)': item.usage_amount,
          }))
          exportExcel(list, tHeader,'缴费报表')
          setTimeout(() => {
            this.exportLoading = false
          }, 1.5 * 1000)
        }
      })
    },
    resetQueryParams(){
      this.listQuery = {
        area_code:'',
        floor:'',
        start:'',
        end:'',
        is_contains_sub: this.$store.getters.showSubData,
        room_number:'',
        unit:'',
        max:0,
        device_code:'',
        date_range:[''],
        page:1,
        pageSize:20
      }
    }
  }
}
</script>
